package edu.gatech.cc.CFAWaffleFriesWheresMyStuff.gui;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import edu.gatech.cc.CFAWaffleFriesWheresMyStuff.R;
import edu.gatech.cc.CFAWaffleFriesWheresMyStuff.common.Datastore;
import edu.gatech.cc.CFAWaffleFriesWheresMyStuff.common.DatastoreFactory;
import edu.gatech.cc.CFAWaffleFriesWheresMyStuff.common.UserManager;
import edu.gatech.cc.CFAWaffleFriesWheresMyStuff.common.UserManager.EmptyFieldException;
import edu.gatech.cc.CFAWaffleFriesWheresMyStuff.common.UserManager.InvalidCharacterException;
import edu.gatech.cc.CFAWaffleFriesWheresMyStuff.common.UserManager.UserExistsException;
import edu.gatech.cc.CFAWaffleFriesWheresMyStuff.common.User;

/**
 * Shows the form for registering a new user with the app.
 * @author Matthew Barulic
 *
 */
public class RegistrationActivity extends Activity {

	private UserManager _userManager;
	
	private boolean _isAdmin;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_registration);
		Bundle extras = getIntent().getExtras();
		
		if(extras != null)
			_isAdmin = extras.getBoolean("isAdmin", false);
		else
			_isAdmin = false;
		
		Datastore ds = DatastoreFactory.getDatastore(getApplicationContext());
		_userManager = new UserManager(ds);
		
		final RegistrationActivity me = this;
		
		((TextView)findViewById(R.id.registrationPassConfirmLabel)).setTextColor(Color.RED);
		
		((EditText)findViewById(R.id.registrationPasswordConfirmText)).addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				me.updateUI();
			}
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
			@Override
			public void afterTextChanged(Editable s) {}
		});
		
		((EditText)findViewById(R.id.registrationPasswordText)).addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				me.updateUI();
			}
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
			@Override
			public void afterTextChanged(Editable s) {}
		});
		
		((EditText)findViewById(R.id.registrationUsernameText)).addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				me.updateUI();
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
			
			@Override
			public void afterTextChanged(Editable s) { }
		});
		
		((EditText)findViewById(R.id.registrationEmailText)).addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				me.updateUI();
			}
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
			@Override
			public void afterTextChanged(Editable s) {}
		});
		
		((EditText)findViewById(R.id.registrationPhonenumberText)).addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				me.updateUI();
			}
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
			@Override
			public void afterTextChanged(Editable s) {}
		});
		
		((Button)findViewById(R.id.registrationRegisterButton)).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				me.registerUser();
			}
		});
		
		((Button)findViewById(R.id.registrationCancelButton)).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				me.goBackToLogin();
			}
		});
		
	}
	
	/**
	 * Update the enabled status of the register button
	 * and displays the "passwords must match" label
	 * when the password and confirm password fields
	 * do not match.
	 */
	private void updateUI()
	{
		String username = ((EditText)findViewById(R.id.registrationUsernameText)).getText().toString();
		String password = ((EditText)findViewById(R.id.registrationPasswordText)).getText().toString();
		String passwordConfirm = ((EditText)findViewById(R.id.registrationPasswordConfirmText)).getText().toString();
		String email = ((EditText)findViewById(R.id.registrationEmailText)).getText().toString();
		String phonenumber = ((EditText)findViewById(R.id.registrationPhonenumberText)).getText().toString();
		
		//Check passwords match
		if(!password.equals(passwordConfirm))
		{
			((TextView)findViewById(R.id.registrationPassConfirmLabel)).setVisibility(View.VISIBLE);
		} else {
			((TextView)findViewById(R.id.registrationPassConfirmLabel)).setVisibility(View.INVISIBLE);
		}
		
		// Update button enabled
		if(username.isEmpty() || password.isEmpty() || passwordConfirm.isEmpty() || email.isEmpty() || phonenumber.isEmpty() || !password.equals(passwordConfirm))
		{
			((Button)findViewById(R.id.registrationRegisterButton)).setEnabled(false);
			((Button)findViewById(R.id.registrationRegisterButton)).setTextColor(Color.BLACK);
		} else {
			((Button)findViewById(R.id.registrationRegisterButton)).setEnabled(true);
			((Button)findViewById(R.id.registrationRegisterButton)).setTextColor(Color.WHITE);
		}
		
	}
	
	/**
	 * Attempts to register a new user with the system.
	 * If this succeeds, the HomeScreenActivity is
	 * started.
	 */
	private void registerUser()
	{
		String username = ((EditText)findViewById(R.id.registrationUsernameText)).getText().toString();
		String password = ((EditText)findViewById(R.id.registrationPasswordText)).getText().toString();
		String confirmPassword = ((EditText)findViewById(R.id.registrationPasswordConfirmText)).getText().toString();
		
		if(!password.equals(confirmPassword))
		{
			AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
			alertDialogBuilder.setTitle("Registration Failed");
			alertDialogBuilder.setMessage("Passwords must match");
			alertDialogBuilder.setCancelable(false);
			alertDialogBuilder.setNeutralButton("OK", null);
			AlertDialog alert = alertDialogBuilder.create();
			alert.show();
		}
		
		String phonenumber = ((EditText)findViewById(R.id.registrationPhonenumberText)).getText().toString();
		String email = ((EditText)findViewById(R.id.registrationEmailText)).getText().toString();
		
		try {
			User registeredUser = null;
			if(_isAdmin)
				registeredUser = _userManager.attemptRegisterAdmin(username, password, "name", email, phonenumber);
			else
				registeredUser = _userManager.attemptRegister(username, password, "name", email, phonenumber);
			Intent i = new Intent(getApplicationContext(), HomeScreenActivity.class);
			i.putExtra("user", registeredUser.getUsername());
			startActivity(i);
			finish();
		} catch (EmptyFieldException e) {
			AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
			alertDialogBuilder.setTitle("Registration Failed");
			alertDialogBuilder.setMessage("Please complete all fields");
			alertDialogBuilder.setCancelable(false);
			alertDialogBuilder.setNeutralButton("OK", null);
			AlertDialog alert = alertDialogBuilder.create();
			alert.show();
		} catch (UserExistsException e) {
			AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
			alertDialogBuilder.setTitle("Registration Failed");
			alertDialogBuilder.setMessage("This username is already registered.");
			alertDialogBuilder.setCancelable(false);
			alertDialogBuilder.setNeutralButton("OK", null);
			AlertDialog alert = alertDialogBuilder.create();
			alert.show();
		} catch (InvalidCharacterException e) {
			AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
			alertDialogBuilder.setTitle("Registration Failed");
			alertDialogBuilder.setMessage("INVALID CHARACTER.");
			alertDialogBuilder.setCancelable(false);
			alertDialogBuilder.setNeutralButton("OK", null);
			AlertDialog alert = alertDialogBuilder.create();
			alert.show();
		}
	}
	
	@Override
	public void onBackPressed()
	{
		goBackToLogin();
	}
	
	/**
	 * Returns to the login screen.
	 * Finishes this activity.
	 */
	private void goBackToLogin()
	{
		Intent i = new Intent(getApplicationContext(), LoginActivity.class);
		startActivity(i);
		finish();
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_registration, menu);
		return true;
	}

}
